/** 功德主列表 */
const cloud = require('wx-server-sdk')
cloud.init({env: 'evn-cloud-a-4gf1q6iy9df62d73'})
const db = cloud.database()
const MAX_LIMIT = 100

const getAdminAndResuce = async() => {
  const adminQuery = await db.collection("kindPersonInfo").where({roles: "管理员"}).get({})
  const rescueQuery = await db.collection("kindPersonInfo").where({roles: "救生员"}).get({})
  console.log("管理员查询结果： ",adminQuery,"救生员查询结果： ",rescueQuery)
  return {adminList: adminQuery.data, rescueList: rescueQuery.data}
}

const main = async (event) => {
  const searchInfo = event.searchInfo
  const sign = event.sign
  //查询所有的管理员和救生员
  if(sign != '' && sign != undefined && sign == "getAdminAndResuce"){
    console.log("查询所有管理员和救生员, sign: ", sign)
    return await getAdminAndResuce()
  }
  const query = db.collection('kindPersonList').where({
    meritsVirtues: {
      $regex: searchInfo == null ? '' : searchInfo,
      $options: 's'
    }
  })
  // 先取出集合记录总数
  const queryResult = await query.count()
  const total = queryResult.total
  console.log("根据条件查询数据总条数结束，数据总条数(total)为：",total,'查询总条数返回的结果（queryResult）为：',queryResult)
  if(total == 0) { return {data: undefined, errMsg: "查询结果为空"}}
  // 计算需分几次取
  const batchTimes = Math.ceil(total / 100)
  // 承载所有读操作的 promise 的数组
  const tasks = []
  for (let i = 0; i < batchTimes; i++) {
    const promise = query.skip(i * MAX_LIMIT).limit(MAX_LIMIT).get({})
    tasks.push(promise)
  }
  console.log('根据条件已查询到数据，合并后的数据(tasks)为：',tasks)
  // 等待所有
  return (await Promise.all(tasks)).reduce((acc, cur) => {
    return { data: acc.data.concat(cur.data), errMsg: acc.errMsg}
  })
}

module.exports = {
  main
}